package com.app.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.app.model.Role;

@Repository
public class RoleDao {
	@Resource
	private JdbcTemplate jdbcTemplate;
	
	private class RoleRowMapper implements RowMapper<Role>{
			@Override
			public Role mapRow(ResultSet rs, int rowNum) throws SQLException {
				Role role = new Role();
				role.setId(rs.getLong("id"));
				role.setName(rs.getString("name"));
				return role;
			}   
	}
	
	public List<Role> findAllByPage(String sql){
		//String final_sql = sql + String.format(" limit %d, %d ", start, pageSize);
		return jdbcTemplate.query(sql, new RoleRowMapper());
	}

	public Integer getCount(String sql) {
		return jdbcTemplate.queryForObject(sql, Integer.class);
	}

	public void save(Role role) {
		String sql = "insert into auth_role(name) values(?)";  
        Object args[] = {role.getName()};  
        jdbcTemplate.update(sql, args);  
	}
	
	public void update(Role role) {
		String sql = "update auth_role set name = ? where id = ?";  
        Object args[] = {role.getName(),role.getId()};  
        jdbcTemplate.update(sql, args);  
	}
	
	//删除  
    public void delete(Long id) {  
        String sql = "delete from auth_role where id = ?";  
        Object args[] = new Object[]{id};  
        jdbcTemplate.update(sql,args);  
    }

	public Role getById(Long id) {
		String sql = "select * from auth_role where id = ?";  
        Object args[] = new Object[]{id};  
        Role  role = jdbcTemplate.queryForObject(sql,args,new BeanPropertyRowMapper(Role.class));  
        return role;  
	}  
}
